package cn.wolfcode.luowowo.website.web.controller;

import cn.wolfcode.luowowo.article.domain.Destination;
import cn.wolfcode.luowowo.article.domain.StrategyDetail;
import cn.wolfcode.luowowo.article.domain.Travel;
import cn.wolfcode.luowowo.article.query.TravelQuery;
import cn.wolfcode.luowowo.article.service.IDestinationService;
import cn.wolfcode.luowowo.article.service.IStrategyDetailService;
import cn.wolfcode.luowowo.article.service.ITravelService;
import cn.wolfcode.luowowo.cache.service.ITravelRedisService;
import cn.wolfcode.luowowo.comment.domain.TravelComment;
import cn.wolfcode.luowowo.comment.query.TravelCommentQuery;
import cn.wolfcode.luowowo.comment.service.ITravelCommentService;
import cn.wolfcode.luowowo.common.util.AJaxResult;
import cn.wolfcode.luowowo.member.domain.UserInfo;
import cn.wolfcode.luowowo.website.annotation.RequireLogin;
import cn.wolfcode.luowowo.website.annotation.UserParam;
import cn.wolfcode.luowowo.website.util.UMEditorUploader;
import com.alibaba.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@Controller
@RequestMapping("travel")
public class TravelController {
    @Reference
    private ITravelService travelService;

    @Reference
    private IStrategyDetailService strategyDetailService;

    @Reference
    private IDestinationService destinationService;

    @Reference
    private ITravelCommentService commentService;

    @Reference
    private ITravelRedisService travelRedisService;
    @Reference
    private ITravelCommentService travelCommentService;

    @RequestMapping("")
    public String index(@ModelAttribute("qo")TravelQuery qo, Model model){
        model.addAttribute("pageInfo",travelService.query(qo));
        //1.先随机查询出3个中国省份目的地
        //2.在根据目的地查询目的地下的攻略明细
            List<StrategyDetail> top3 = strategyDetailService.getTopViewnum3ByDestId(1L);
        List<Destination> randomList = destinationService.getRandomList(top3, 2);
        model.addAttribute("randomList",randomList);

        //前5个旅游攻略
        //tcs 前十个推荐游记,有顺序问题
        TravelCommentQuery query = new TravelCommentQuery();
        query.setCurrentPage(1);//不分页,
        query.setPageSize(10);//查询前10

        query.setTravelId(query.getTravelId());
        Page page = travelCommentService.query(query);
        model.addAttribute("tcs", page.getContent());

        return "travel/list";
    }

    @RequestMapping("detail")
    public String detail(Long id,Model model,@UserParam UserInfo userInfo){
        Travel travel = travelService.get(id);
        model.addAttribute("detail", travel);
        //toasts
        List<Destination> toasts = destinationService.getToasts(travel.getDest().getId());
        toasts.remove(toasts.size()-1);
        model.addAttribute("toasts",toasts);
        //sds
        model.addAttribute("sds",
                strategyDetailService.getTopViewnum3ByDestId(travel.getDest().getId()));
        model.addAttribute("ts",
                travelService.getViewNumTop3ByDestId(travel.getDest().getId(),id));
        TravelCommentQuery qo = new TravelCommentQuery();
        qo.setPageSize(Integer.MAX_VALUE);
        qo.setTravelId(id);
        Page<TravelComment> page = commentService.query(qo);
        model.addAttribute("list", page.getContent());

        travelRedisService.viewNumIncrease(id,1);
        model.addAttribute("vo",travelRedisService.getStatisVo(id));
        //isFavor
        if(userInfo != null){
            model.addAttribute("isFavor",travelRedisService.isFavor(id,userInfo.getId()));
        }
        return "travel/detail";
    }

    @RequestMapping("input")
    @RequireLogin
    public String input(Long id,Model model){
        model.addAttribute("dests",destinationService.getDestByDeep(3));
        if(id != null){
            model.addAttribute("tv",travelService.get(id));
        }
        return "travel/input";
    }

    @RequestMapping("getContent")
    @ResponseBody
    public String getContent(Long id){
        return travelService.get(id).getTravelContent().getContent();
    }

    @RequestMapping("saveOrUpdate")
    @ResponseBody
    public AJaxResult saveOrUpdate(Travel travel,@UserParam UserInfo userInfo){
        travel.setAuthor(userInfo);
        Long detailId = travelService.saveOrUpdate(travel);
        return AJaxResult.SUCCESS().addData(detailId);
    }

    @Value("${file.path}")
    private String filePath;
    //上传图片
    @RequestMapping("/contentImage")
    @ResponseBody
    public String uploadUEImage(MultipartFile upfile, HttpServletRequest request) throws Exception{
        UMEditorUploader up = new UMEditorUploader(request);
        String[] fileType = {".gif" , ".png" , ".jpg" , ".jpeg" , ".bmp"};
        up.setAllowFiles(fileType);
        up.setMaxSize(10000); //单位KB
        up.upload(upfile, filePath);

        String callback = request.getParameter("callback");
        String result = "{\"name\":\""+ up.getFileName() +"\", \"originalName\": \""+ up.getOriginalName() +"\", \"size\": "+ up.getSize()
                +", \"state\": \""+ up.getState() +"\", \"type\": \""+ up.getType() +"\", \"url\": \""+ up.getUrl() +"\"}";
        result = result.replaceAll( "\\\\", "\\\\" );
        if(callback == null ){
            return result ;
        }else{
            return "<script>"+ callback +"(" + result + ")</script>";
        }
    }


    @RequestMapping("commentAdd")
    @RequireLogin
    public String commentAdd(TravelComment comment,@UserParam UserInfo userInfo,Model model, int floor){
        comment.setUserId(userInfo.getId());
        comment.setCity(userInfo.getCity());
        comment.setHeadUrl(userInfo.getHeadImgUrl());
        comment.setLevel(userInfo.getLevel());
        comment.setUsername(userInfo.getNickname());
        model.addAttribute("floor",floor+1);
        model.addAttribute("c",commentService.addComment(comment));
        return "travel/commentTpl";
    }

    @RequestMapping("favor")
    @ResponseBody
    public AJaxResult favor(Long sid,@UserParam UserInfo userInfo){
        if(userInfo == null){
            AJaxResult aJaxResult = new AJaxResult(false,"请登录后再收藏!");
            aJaxResult.setCode(102);
            return aJaxResult;
        }
        boolean ret = travelRedisService.favor(sid,userInfo.getId());

        if(ret){
            travelService.saveFavorToUser(sid, userInfo.getId ());
        }else{
            travelService.deleteUserFavor(userInfo.getId (), sid);
        }


        return new AJaxResult(ret, "").addData(travelRedisService.getStatisVo(sid));
    }

    @RequestMapping("travelThumbup")
    @ResponseBody
    public AJaxResult travelThumbup(Long sid,@UserParam UserInfo userInfo){
        if(userInfo == null){
            AJaxResult aJaxResult = new AJaxResult(false,"请登录后再顶!");
            aJaxResult.setCode(102);
            return aJaxResult;
        }
        boolean ret = travelRedisService.travelThumbup(sid,userInfo.getId());
        return new AJaxResult(ret, "").addData(travelRedisService.getStatisVo(sid));
    }

    @RequestMapping("share")
    @ResponseBody
    public AJaxResult share(Long sid){
        travelRedisService.travelShare(sid,1);
        return AJaxResult.SUCCESS().addData(travelRedisService.getStatisVo(sid));
    }
}
